package com.sinosun.autotestmachine.tools.parser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.ValueInfo;
import com.sinosun.autotestmachine.tools.ValueType;
import com.sinosun.autotestmachine.tools.Collector.Cache;
import com.sinosun.autotestmachine.tools.utils.MimeType;
import com.sinosun.autotestmachine.tools.utils.Utils;
import com.sinosun.mstplib.message.AudioMessageBody;
import com.sinosun.mstplib.message.BusinessType;
import com.sinosun.mstplib.message.ChatType;
import com.sinosun.mstplib.message.FileMessageBody;
import com.sinosun.mstplib.message.ImageMessageBody;
import com.sinosun.mstplib.message.Message;
import com.sinosun.mstplib.message.MessagePriority;
import com.sinosun.mstplib.message.TextMessageBody;
import com.sinosun.mstplib.message.VideoMessageBody;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.Log;


/**
 * 内容提器
 * @author HYW
 *
 */
public class ContentMaker {
	
	public static Message makeMessage(String Message, String from) throws JSONException {
		Message msg = new Message();
		msg.setFrom(from);
		msg.setBusinessType(BusinessType.IM);
		
		JSONObject msgJO = new JSONObject(Message);
		if (msgJO.has(ParamKey.BODY_CONTENT)) {
			JSONObject contentJo = msgJO.getJSONObject(ParamKey.BODY_CONTENT);
			if (contentJo.has(ParamKey.CHAT_TYPE)) {			//发送消息类型
				msg.setChatType(ChatType.valueOf(contentJo.getInt(ParamKey.CHAT_TYPE)));
				
			}
			
			JSONArray toArray = null;
			if (contentJo.has(ParamKey.TO)) {
				toArray = contentJo.getJSONArray(ParamKey.TO);
			}
			
			if (msg.getChatType() == ChatType.P2P) {		//消息类型下取出对应的 mstpId -> P2P
				if (toArray == null) return null;
				if (toArray.length() > 1) {
					for (int k = 0; k < toArray.length(); k++) {
						ValueInfo value = Utils.getUserRealInfo((String) toArray.get(k));
						String toMstpId;
						if (value.getValueType() == ValueType.INDEX) {
							toMstpId = App.getTestConfig().getUsers().get(value.getValueContent());
						} else {
							toMstpId = value.getValueContent();
						}
						if (TextUtils.isEmpty(toMstpId)) {
							return null;
						}
						msg.addTo(toMstpId);
					}
				} else if (toArray.length() == 1) {
					ValueInfo value = Utils.getUserRealInfo((String) toArray.get(0));
					String toMstpId;
					if (value.getValueType() == ValueType.INDEX) {
						toMstpId = App.getTestConfig().getUsers().get(value.getValueContent());
					} else {
						toMstpId = value.getValueContent();
					}
					if (TextUtils.isEmpty(toMstpId)) {
						return null;
					}
					msg.setTo(toMstpId);
				} else {
					return null;
				}
				
			} else if (msg.getChatType() == ChatType.GROUP) {	//消息类型下取出对应的 mstpId -> GROUP
				if (toArray != null) {
					for (int i = 0; i < toArray.length(); i++) {
						ValueInfo value = Utils.getUserRealInfo((String) toArray.get(i));
						String toMstpId;
						if (value.getValueType() == ValueType.INDEX) {
							toMstpId = App.getTestConfig().getUsers().get(value.getValueContent());
						} else {
							toMstpId = value.getValueContent();
						}
						if (TextUtils.isEmpty(toMstpId)) {
							return null;
						}
						msg.addTo(toMstpId);
					}
				}
				
				if (contentJo.has(ParamKey.GROUP_ID)) {			//群聊的 groupId
					String groupId = contentJo.getString(ParamKey.GROUP_ID);
					ValueInfo vi = Utils.getGroupMstpInfo(groupId);
					if (vi.getValueType() == ValueType.INDEX) {
						if (contentJo.has(ParamKey.BUSINESS_TYPE)) {
							msg.setBusinessType(BusinessType.valueOf(contentJo.getInt(ParamKey.BUSINESS_TYPE)));
							groupId = Cache.allTopicInfo.get(groupId).getTopic().getTopicId();
						} else {
							groupId = Cache.groupInfoCache.get(groupId).getMstpId();
						}
					}
					
					if (groupId != null) {
						msg.setGroupId(groupId);
					} else {
						return null;
					}
				}
			} else {		//不时群组也不是点对点消息暂不处理
				return null;
			}
			
			if (contentJo.has(ParamKey.PRIORITY)) {
				msg.setPriority(MessagePriority.valueOf(contentJo.getInt(ParamKey.PRIORITY)));
			}
			
			if (contentJo.has(ParamKey.NEED_REPLY)) {
				msg.setNeedReply(contentJo.getBoolean(ParamKey.NEED_REPLY));
			}
			
			if (contentJo.has(ParamKey.PUSH_TYPE)) {
				msg.setPushType(contentJo.getInt(ParamKey.PUSH_TYPE));
			}
			
			msg.setExpTime(System.currentTimeMillis() / 1000 + 7 * 24 * 3600);
			msg.setTimestamp(System.currentTimeMillis() / 1000);
				
			if (contentJo.has(ParamKey.EXTATTR)) {
				Map<String, String> exattrs = new HashMap<String, String>();
				Map<String, Object> tmp = JSON.parseObject(contentJo.getString(ParamKey.EXTATTR));
				for (String key : tmp.keySet()) {
					ValueInfo vi = Utils.getSendRealInfo(String.valueOf(tmp.get(key)));
					if (vi.getValueType() == ValueType.CONTENT) {
						exattrs.put(key, String.valueOf(tmp.get(key)));
					} else {
						if (Cache.messageSendCache.get(String.valueOf(tmp.get(key))) != null) {
							exattrs.put(key, Cache.messageSendCache.get(String.valueOf(tmp.get(key))).getMsgId());
						} else {
							exattrs.put(key, null);
						}
					}
				}
				msg.setExtAttrs(exattrs);
			}
			
			if (contentJo.has(ParamKey.MSG_BODY)) {
				JSONArray bodyContent = new JSONArray(contentJo.getString(ParamKey.MSG_BODY));
				for (int j = 0; j < bodyContent.length(); j++) {
					JSONObject bodyJO = bodyContent.getJSONObject(j);
					if (bodyJO.has(ParamKey.BODY_TYPE)) {
						int tag = bodyJO.getInt(ParamKey.BODY_TYPE);
						switch(tag) {
						case 10:				//普通文本
						case 11:				//文字
						case 12:				//emoji
							int txtLen = 0;
							if (bodyJO.has(ParamKey.SIZE)) {
								txtLen = bodyJO.getInt(ParamKey.SIZE);
							} else {		//字符串没有给出长度，无法生成
								return null;
							}
							String txt = new String();
							if (tag == 11) {
								txt = getRandomChinese(txtLen);
							} else if (tag == 12) {
								txt = getRandomEmoji(txtLen);
							} else if (tag == 10) {
								if (txtLen != 0) {
									txt = random(txtLen);
								} else {
									txt = "";
								}
							}
							TextMessageBody tmb = new TextMessageBody(txt);
							if (bodyJO.has(ParamKey.EXT_INFO)) {
								tmb.setExtInfo(bodyJO.getString(ParamKey.EXT_INFO));
							}
							msg.addMessageBody(tmb);
							break;
						case 20:				//生成普通文件Body
							long fileSize = 0;
							if (bodyJO.has(ParamKey.SIZE)) {
								fileSize = bodyJO.getLong(ParamKey.SIZE);
							} else {		//字符串没有给出长度，无法生成
								return null;
							}
							
							String fileName = generateSizedFile(App.getInstance().getUploadPath(), (int)fileSize, null);
							
							FileMessageBody fmb = new FileMessageBody();
							fmb.setFilePath(App.getInstance().getUploadPath() + fileName);
							fmb.setFileName(fileName);
							fmb.setSize(fileSize);
							fmb.setMimeType(MimeType.getMimeType(App.getInstance().getUploadPath() + fileName));
							
							if (bodyJO.has(ParamKey.EXT_INFO)) {
								fmb.setExtInfo(bodyJO.getString(ParamKey.EXT_INFO));
							}
							msg.addMessageBody(fmb);
							break;
						case 30:	//图片消息
							long imgSize = 0;
							if (bodyJO.has(ParamKey.SIZE)) {
								imgSize = bodyJO.getLong(ParamKey.SIZE);
							} else {		//字符串没有给出长度，无法生成
								return null;
							}
							
							JSONArray imgPolicyArr = new JSONArray();
							int w,h,e,l,q;
							w = h = e = l = q = -1;
							if (bodyJO.has(ParamKey.IMAGE_POLICY)) {
								JSONArray oriArray = bodyJO.getJSONArray(ParamKey.IMAGE_POLICY);
								for (int k = 0; k < oriArray.length(); k++) {
									JSONObject policyObj = oriArray.getJSONObject(k);
									JSONObject imgPolicyObject = new JSONObject();
									if (policyObj.has(ParamKey.W)) {
										w = policyObj.getInt(ParamKey.W);
										imgPolicyObject.put(ParamKey.W, w);
									}
									if (policyObj.has(ParamKey.H)) {
										h = policyObj.getInt(ParamKey.H);
										imgPolicyObject.put(ParamKey.H, h);
									}
									if (policyObj.has(ParamKey.E)) {
										e = policyObj.getInt(ParamKey.E);
										imgPolicyObject.put(ParamKey.E, e);
									}
									
									if (policyObj.has(ParamKey.L)) {
										l = policyObj.getInt(ParamKey.L);
										imgPolicyObject.put(ParamKey.L, l);
									}
									
									if (policyObj.has(ParamKey.Q)) {
										q = policyObj.getInt(ParamKey.Q);
										imgPolicyObject.put(ParamKey.Q, q);
									}
									imgPolicyArr.put(imgPolicyObject);
								}
							}
							
							String imgName = generateImageFile(App.getInstance().getUploadPath(), null);
							ImageMessageBody imb = new ImageMessageBody();
							imb.setFilePath(App.getInstance().getUploadPath() + imgName);
							imb.setFileName(imgName);
							imb.setSize(imgSize);
							imb.setMimeType(MimeType.getMimeType(App.getInstance().getUploadPath() + imgName));
							
							if (h != -1 || w != -1 || e != -1 || l != -1 || q != -1) {
								imb.setImagePolicy(imgPolicyArr.toString());
							}
							
							if (bodyJO.has(ParamKey.EXT_INFO)) {
								imb.setExtInfo(bodyJO.getString(ParamKey.EXT_INFO));
							}
							msg.addMessageBody(imb);
							break;
						case 40:	//音频消息
							long audioSize = 0;
							if (bodyJO.has(ParamKey.SIZE)) {
								audioSize = bodyJO.getLong(ParamKey.SIZE);
							} else {		//字符串没有给出长度，无法生成
								return null;
							}
							
							String audioName = generateSizedAudioFile(App.getInstance().getUploadPath(), (int)audioSize, null);
							AudioMessageBody amb = new AudioMessageBody();
							amb.setFilePath(App.getInstance().getUploadPath() + audioName);
							amb.setFileName(audioName);
							amb.setSize(audioSize);
							amb.setMimeType(MimeType.getMimeType(App.getInstance().getUploadPath() + audioName));
							amb.setDuration(10);
							
							if (bodyJO.has(ParamKey.EXT_INFO)) {
								amb.setExtInfo(bodyJO.getString(ParamKey.EXT_INFO));
							}
							msg.addMessageBody(amb);
							break;
						case 50:	//视频消息
							long videoSize = 0;
							if (bodyJO.has(ParamKey.SIZE)) {
								videoSize = bodyJO.getLong(ParamKey.SIZE);
							} else {		//字符串没有给出长度，无法生成
								return null;
							}
							
							String videoName = generateSizedVideoFile(App.getInstance().getUploadPath(), (int)videoSize, null);
							VideoMessageBody vmb = new VideoMessageBody();
							vmb.setFilePath(App.getInstance().getUploadPath() + videoName);
							vmb.setFileName(videoName);
							vmb.setSize(videoSize);
							vmb.setMimeType(MimeType.getMimeType(App.getInstance().getUploadPath() + videoName));
							vmb.setDuration(10);
							
							if (bodyJO.has(ParamKey.EXT_INFO)) {
								vmb.setExtInfo(bodyJO.getString(ParamKey.EXT_INFO));
							}
							msg.addMessageBody(vmb);
							break;
						}
					}
				}
			}
		}
		return msg;
	}
	
	public static FileInfoHolder getFileInfoHolder(String param) {
		try {
			FileInfoHolder ret = new FileInfoHolder();
			JSONObject jo = new JSONObject(param);
			if (jo.has(ParamKey.DESC)) {
				if (jo.isNull(ParamKey.DESC)) {
					ret.setDescription(null);
				}
				ret.setDescription(jo.getString(ParamKey.DESC));
			}
			if (jo.has(ParamKey.FILE_TYPE)) {
				ret.setFileType(jo.getInt(ParamKey.FILE_TYPE));
			}
			if (jo.has(ParamKey.FILE_SIZE)) {
				ret.setFileSize(jo.getLong(ParamKey.FILE_SIZE));
			}
			if (jo.has(ParamKey.ENCRYPT)) {
				ret.setEncrypt(jo.getInt(ParamKey.ENCRYPT));
			}
			if (jo.has(ParamKey.IMAGE_POLICY)) {
				if (jo.isNull(ParamKey.IMAGE_POLICY)) {
					ret.setImagePolicy(null);
				}
				ret.setImagePolicy(jo.getString(ParamKey.IMAGE_POLICY));
			}
			if (jo.has(ParamKey.FILE_NAME)) {
				if (jo.isNull(ParamKey.FILE_NAME)) {
					ret.setFileName(null);
				}
				ret.setFileName(jo.getString(ParamKey.FILE_NAME));
			}
			return ret;
		} catch (JSONException e) {
			return null;
		}
	}
	
	//生成指定长度的字符串（字母）
	public static String random(int length) {
		Random random = new Random();
		StringBuilder builder = new StringBuilder(length);
		for (int i = 0; i < length; i++) {
			builder.append((char) (random.nextInt(26) + 65));
		}
		return builder.toString();
	}
	
	private static char getRandomChar() {  
        String str = "";  
        int hightPos;  
        int lowPos;  
  
        Random random = new Random();  
  
        hightPos = (176 + Math.abs(random.nextInt(39)));  
        lowPos = (161 + Math.abs(random.nextInt(93)));  
  
        byte[] b = new byte[2];  
        b[0] = (Integer.valueOf(hightPos)).byteValue();  
        b[1] = (Integer.valueOf(lowPos)).byteValue();  
  
        try {  
            str = new String(b, "GBK");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return str.charAt(0);  
    }
	
	public static String getRandomChinese(int len) {
		String ret = new String("");
		for (int i = 0; i < len; i++) {
			ret = ret + getRandomChar();
		}
		return ret;
	}
	
	public static String getRandomEmoji(int len) {
		String ret = new String("");
		for (int i = 0; i < len; i++) {
			ret = ret + getEmoji();
		}
		return ret;
	}
	
	private static String getEmoji(){  
	    int unicodeJoy = 0x1F602;  
	    return new String(Character.toChars(unicodeJoy));
	}

	/**
	 * 生成指定路径的图片
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateImageFile(String filePath, String tmpName) {
		String fileName = new String("");
		if (TextUtils.isEmpty(tmpName)) {
			fileName = random(8) + ".jpg";
		} else {
			fileName = tmpName + ".jpg";
		}
		int width = 100;
		int height = 100;
		Bitmap bitmap = Bitmap.createBitmap(width, height,Config.ARGB_8888);	//创建一个你需要尺寸的Bitmap
		Canvas canvas = new Canvas(bitmap);				//用这个Bitmap生成一个Canvas,然后canvas就会把内容绘制到上面这个bitmap中

		Paint paint = new Paint();//定义一个画笔
		paint.setColor(Color.RED);//红色画笔
		paint.setTextSize(35);
        float x = 0;
        float y = 100;
		canvas.drawText(fileName, x, y , paint);//绘制文案
        File image = new File(filePath + fileName);  
        OutputStream stream = null;
		try {
			stream = new FileOutputStream(image);
	        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);  
	        stream.close(); 
		} catch (Exception e) {
			
		}  
 
		return fileName;
	}

	/**
	 * 随机生成指定路径的文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateFile(String filePath, String fileName) {
		return generateFile(filePath, ".txt", fileName);
	}
	
	/**
	 * 随机生成指定路径的文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	private static String generateFile(String filePath, String type, String tmpName) {
		String name;
		if (TextUtils.isEmpty(tmpName)) {
			name = random(8);
		} else {
			name = tmpName;
		}
		
		BufferedWriter fw;
		String fileName = filePath + name + type;
		try {
			fw = new BufferedWriter(new FileWriter(fileName, true));
			fw.newLine();
			fw.append("我是被写入txt的字符串" + System.currentTimeMillis());
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return name + type;
	}
	
	/**
	 * 随机生成指定路径的音频文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateAudioFile(String filePath, String fileName) {
		return generateFile(filePath, ".mp3", fileName);
	}
	
	/**
	 * 随机生成指定路径的视频文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateVideoFile(String filePath, String fileName) {
		return generateFile(filePath, ".mp4", fileName);
	}
	
	/**
	 * 随机生成指定路径大小的音频文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateSizedAudioFile(String filePath, int size, String fileName) {
		return generateSizedFile(filePath, ".mp3", size, fileName);
	}
	
	/**
	 * 随机生成指定路径大小的视频文件
	 * 
	 * @param filePath
	 *            生成文件的路径
	 * @return 返回文件名
	 */
	public static String generateSizedVideoFile(String filePath, int size, String fileName) {
		return generateSizedFile(filePath, ".mp4", size, fileName);
	}
	
	/**
	 * 随机生成指定大小的文件
	 * 
	 * @param filePath
	 *            文件指定路径
	 * @param size
	 *            单位为M
	 * @return 文件名
	 */
	public static String generateSizedFile(String filePath, int size, String fileName) {
		return generateSizedFile(filePath, ".txt", size, fileName);
	}

	/**
	 * 随机生成指定大小类型的文件
	 * 
	 * @param filePath
	 *            文件指定路径
	 * @param size
	 *            单位为M
	 * @return 文件名
	 */
	private static String generateSizedFile(String filePath, String type, int size, String tmpName) {
		String name = new String("");
		if (TextUtils.isEmpty(tmpName)) {
			name = random(8);
		} else {
			name = tmpName;
		}
		BufferedWriter fw = null;
		String fileName = filePath + name + type;
		File dirFile = new File(filePath);		//保证路径存在
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
		File file = new File(fileName);			//删除已经存在的同名文件
		if (file.exists()) {
			file.delete();
		}
		
		try {									//创建空的文件
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		int activeSize = 100;
		if (size > activeSize) {		//大于 100 字节的使用快速生成
			try {
				createFixLengthFile(file, size, activeSize);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} else {		//小于等于 100 字节使用慢速生成
			activeSize = size;
		}
		
		try {
			fw = new BufferedWriter(new FileWriter(fileName, true));
			String tmp = random(activeSize);
			fw.append(tmp);
			fw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Log.e("XXX", "file name = " + name + type + ", file length = " + file.length());
		return name + type;
	}
	
	public static void createFixLengthFile(File file, long length, int activeSize) throws IOException{  
	    long start = System.currentTimeMillis();  
	    FileOutputStream fos = null;  
	    FileChannel output = null;  
	    try {  
	        fos = new FileOutputStream(file);  
	        output = fos.getChannel();  
	        output.write(ByteBuffer.allocate(1), length - activeSize - 1);
	        fos.flush();
	    } finally {  
	        try {  
	            if (output != null) {  
	                output.close();  
	            }  
	            if (fos != null) {  
	                fos.close();  
	            }  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    long end = System.currentTimeMillis();  
	    System.out.println("total times "+(end - start));  
	}  

	/**
	 * 转化文件大小
	 * 
	 * @param size
	 *            字节大小
	 * @return 文件大小
	 */
	public static String formetFileSize(long size) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (size < 1024) {
			fileSizeString = df.format((double) size) + "B";
		} else if (size < 1048576) {
			fileSizeString = df.format((double) size / 1024) + "K";
		} else if (size < 1073741824) {
			fileSizeString = df.format((double) size / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) size / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 指定路径创建文件夹
	 * 
	 * @param path
	 *            指定目录
	 * @return 成功返回true，失败返回false
	 */
	public static boolean createDir(final String path) {
		boolean result = false;

		if (TextUtils.isEmpty(path)) {
			return result;
		}
		File cache = new File(path);
		if (cache.isFile()) {
			cache.delete();
		}

		if (!cache.exists()) {
			result = cache.mkdirs();
		}
		return result;
	}

//	/**
//	 * 判断是否sd卡的root目录
//	 * 
//	 * @param path
//	 *            文件路径
//	 * @return 相同返回 true，否则返回 false
//	 */
//	public static boolean isSdcardRootPath(String path) {
//		File sdCardFile = null;
//		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//			sdCardFile = Environment.getExternalStorageDirectory();
//		} else {
//			sdCardFile = Environment.getDataDirectory();
//		}
//		String sdcardPath = sdCardFile.getPath();
//		File sdCard = new File(sdcardPath);
//		File tmpFile = new File(path);
//		return tmpFile.getPath().equals(sdCard.getPath());
//	}

	/**
	 * 获取路径的文件名
	 * 
	 * @param path
	 *            输入路径
	 * @return 文件名
	 */
	public static String getFileName(String path) {
		String ret = path;
		if (!TextUtils.isEmpty(path)) {
			if (!path.endsWith(File.separator)) {
				int lastIndex = path.lastIndexOf(File.separator);
				if (lastIndex != -1) {
					ret = path.substring(lastIndex + 1);
				}
			}
		}
		return ret;
	}
	/**
	 * 删除路径下的文件
	 * 
	 * @param path
	 *            输入路径
	 * @return 文件名
	 */
	public static boolean delAllFile(String path) {
	    boolean flag = false;
	    File file = new File(path);
	    if (!file.exists()) {
	      return flag;
	    }
	    if (!file.isDirectory()) {
	      return flag;
	    }
	    String[] tempList = file.list();
	    File temp = null;
	    for (int i = 0; i < tempList.length; i++) {
	       if (path.endsWith(File.separator)) {
	          temp = new File(path + tempList[i]);
	       } else {
	           temp = new File(path + File.separator + tempList[i]);
	       }
	       if (temp.isFile()) {
	          temp.delete();
	       }
	       if (temp.isDirectory()) {
	          delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
	          flag = true;
	       }
	    }
	    return flag;
	}
	
	public static void cpAssertToFiles(String fileName, String destPath) {
	    File file = new File(destPath);
	    int len;
	
	    if (file.exists()) {
	    	file.delete();
	    }
	    
       	try {
       		file.createNewFile();
		} catch (IOException e3) {
			e3.printStackTrace();
		}
	    	
	    AssetManager assetManager = App.getInstance().getApplicationContext().getAssets();
	    InputStream inputStream = null;
	    FileOutputStream outputStream = null;
	    try {
	        inputStream = assetManager.open(fileName);
	    } catch (IOException e1) {
	        e1.printStackTrace();
	    }
	
	    try {
	        if (inputStream == null) {
	            return;
	        }
	        byte buf[] = new byte[inputStream.available()];
	        if (buf != null) {
	            outputStream = new FileOutputStream(file);
	            while ((len = inputStream.read(buf)) != -1) {
	                outputStream.write(buf, 0, len);
	            }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            if (outputStream != null)
	                outputStream.close();
	            if (inputStream != null)
	                inputStream.close();
	        } catch (Exception e2) {
	            e2.printStackTrace();
	        }
	    }
	}

	public static void cpAssertToFiles(String fileName) {	//拷贝asset中的文件到指定路径
		cpAssertToFiles(fileName, App.getInstance().getTestConfigPath() + fileName);
	}
	
	public static void cpAssertToFiles4Other(String fileName) {
		String path = App.getInstance().getApplicationContext().getFilesDir().getPath() + "/" + fileName;
		
	    File file = new File(path);
	    int len;
	
	    if (!file.exists()) {
	        AssetManager assetManager = App.getInstance().getApplicationContext().getAssets();
	        InputStream inputStream = null;
	        FileOutputStream outputStream = null;
	        try {
	            inputStream = assetManager.open(fileName);
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        }
	
	        try {
	            if (inputStream == null) {
	                return;
	            }
	            byte buf[] = new byte[inputStream.available()];
	            if (buf != null) {
	                outputStream = App.getInstance().getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE);
	                while ((len = inputStream.read(buf)) != -1) {
	                    outputStream.write(buf, 0, len);
	                }
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (outputStream != null)
	                    outputStream.close();
	                if (inputStream != null)
	                    inputStream.close();
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	    }
	}
}
